package cn.rxmind.dlicense.server.api;

import cn.hutool.core.codec.Base64Encoder;
import cn.rxmind.dlicense.core.constants.DLicenseConstants;
import cn.rxmind.dlicense.core.decoder.DLicenseDecoder;
import cn.rxmind.dlicense.core.exception.DLicenseErrEnum;
import cn.rxmind.dlicense.core.exception.DLicenseExceptionFactory;
import cn.rxmind.dlicense.server.dto.CreateLicenseDTO;
import cn.rxmind.dlicense.server.service.LicenseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 证书生成接口
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2021/4/14 9:30 上午
 */
@Slf4j
@RequestMapping("license")
@RestController
@Api(tags = "证书服务端接口")
public class LicenseController {

    private static byte[] publicCertBytes;

    static {

        ClassPathResource classPathResource = new ClassPathResource("license/publicCerts.keystore");
        try(InputStream inputStream = classPathResource.getInputStream()){
            int available = inputStream.available();
            publicCertBytes = new byte[available];
            inputStream.read(publicCertBytes);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private LicenseService licenseService;

    @Autowired
    private DLicenseDecoder licenseDecoder;

    @ApiIgnore
    @PostMapping("/innerToken")
    public String innerToken(HttpServletRequest request){

        // 验证是否为内网环境，内网的判定应该由证书服务端判定，如通过MAC和IP白名单机制，怎么可能完全就是对个暗号就行了呢
        StringBuffer requestURL = request.getRequestURL();

        return Base64Encoder.encode( "身之主宰便是心，意之所在便是物，心物圆融，浑然一体。".getBytes());
    }

    @ApiOperation("枚举参数获取")
    @GetMapping("/typeParam")
    public Map typeMapping(){
        return DLicenseConstants.TYPE_PARAM;
    }

    @ApiOperation("下载公钥")
    @GetMapping(value = "publicCert",produces = MediaType.APPLICATION_JSON_VALUE)
    public void publicCert(){

        write2Response(publicCertBytes,"publicCerts.keystore");
    }

    @ApiOperation("解析证书内容")
    @PostMapping("decode")
    public Object licenseDecode(@RequestParam("license_file") MultipartFile file, HttpServletRequest request) throws Exception {

        return licenseDecoder.decode(file.getBytes());

    }

    @ApiOperation("创建并下载授权证书")
    @PostMapping(value = "create",produces = MediaType.APPLICATION_JSON_VALUE)
    public void createLicense(@RequestBody CreateLicenseDTO dto){
        dto.check();
        byte[] license = licenseService.createLicense(dto.covert2UtryLicenseContent());
        write2Response(license,"license.lic");
    }

    /**
     * 将证书写出到客户端
     * @param licenseBytes
     */
    private void write2Response(byte[] licenseBytes,String fileName){
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        response.setContentType("application/octet-stream;charset=UTF-8");

        try(OutputStream outputStream = response.getOutputStream()){
            outputStream.write(licenseBytes);
            outputStream.flush();
        }catch (IOException e){

            log.error("证书文件写出失败",e);
            throw DLicenseExceptionFactory.buildUtryLicenseException(DLicenseErrEnum.LICENSE_DOWNLOAD_ERROR);
        }

    }

}
